#!/bin/bash
mirror_style release
download_style apt
finddebs_style from-indices
variants - buildd fakechroot minbase
default_mirror https://cf-repo.aosc.io/debs

work_out_debs () {
    required='apt gcc-runtime tar xz gnupg'
    base='admin-base util-base iptables'
}

first_stage_install () {
    # additional packages from `noarch`
    ca_certs="$MIRRORS/pool/stable/main/c/ca-certs_20191125-0_noarch.deb"
    ca_certs_deb="/var/cache/apt/archives/$(basename $ca_certs)"
    get "$ca_certs" "$TARGET/$ca_certs_deb" "4013ef7fac210bb040c28c32b65a9a5ced8fcaccb9bc04c9cd0e8ace8ad05eec" 295504
    echo "ca-certs $ca_certs_deb" >> "$TARGET/debootstrap/debpaths"

    extract 'aosc-aaa' 'ca-certs'
    extract $(without "$required grep" 'aosc-aaa')
    cp -ar "$TARGET/bin/"* "$TARGET/usr/bin/"
    rm -rf "$TARGET/bin/"
    ln -s usr/bin "$TARGET/bin"
    cp -ar "$TARGET/usr/lib64/"* "$TARGET/usr/lib/"
    rm -rf "$TARGET/usr/lib64/"
    ln -s lib "$TARGET/usr/lib64"
    cp -ar "$TARGET/var/run/"* "$TARGET/run/"
    rm -rf "$TARGET/var/run/"
    ln -s /run "$TARGET/var/run"
    mkdir -p "$TARGET/var/lib/dpkg"
    : >"$TARGET/var/lib/dpkg/status"
    : >"$TARGET/var/lib/dpkg/available"
    setup_etc
    setup_devices
}

second_stage_install () {
    in_target /bin/true
    
    setup_dynamic_devices
    curl 'https://repo.aosc.io/aosc-repacks/etc-bootstrap.tar.xz' | tar xJf - -C "$TARGET"
    DEBIAN_FRONTEND=noninteractive
    DEBCONF_NONINTERACTIVE_SEEN=true
    export DEBIAN_FRONTEND DEBCONF_NONINTERACTIVE_SEEN
    
    info INSTCORE "Installing core packages (precondition)..."
    in_target apt-get install -y iptables shadow grep keyutils
    in_target bash -c "echo 'root:anthon' | chpasswd"
    info INSTCORE "Updating package cache..."
    in_target apt-get update
    info INSTCORE "Installing core packages..."
    for i in {0..5}
    do in_target apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confnew" install admin-base util-base systemd-base network-base web-base core-base editor-base python-base bash-startup && \
        break || (warning INSTCORE "Failure while unpacking required packages.  This will be attempted up to five times."; in_target apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confnew" install -f)
    done
    in_target cp -rT /etc/skel /root/
    info BASESUCCESS "Base system installed successfully."
}
